package controller

import (
	"data-system/meta"
	"data-system/models"
	"data-system/page_handle"
	"data-system/tools"
	"fmt"
	"log"

	"github.com/gorilla/websocket"
)

type PageLogicParam struct {
	Key  string                 `json:"key"`
	Data map[string]interface{} `json:"data"`
}

type PageLogicAction struct {
	BaseAction
}

func NewPageLogicAction(action string, channel chan models.XMessage, conn *websocket.Conn, param any) (Handler, error) {
	return &PageLogicAction{BaseAction: BaseAction{
		Action:  action,
		Param:   param,
		Channel: channel,
		Client:  conn,
	}}, nil
}

func (ctx *PageLogicAction) Handle() (any, error) {
	var pageLogicParam PageLogicParam
	err := tools.MapToObj(tools.ObjToMap(ctx.Param), &pageLogicParam)
	if err != nil {
		log.Println("【查询】参数转换失败", err)
		return nil, err
	}
	triggerLogicMeta := meta.GetPageLogicMeta(pageLogicParam.Key)
	if triggerLogicMeta == nil {
		log.Println("【查询】参数转换失败", err)
		return nil, fmt.Errorf("没有找到对应的页面逻辑元数据：key=%v", pageLogicParam.Key)
	}
	ctx.doHandle(triggerLogicMeta, pageLogicParam.Data)
	return nil, nil
}

func (ctx *PageLogicAction) doHandle(logicMeta *models.PageLogicMeta, data map[string]interface{}) {
	handleCtx := models.PageLogicHandleCtx{Meta: logicMeta, Data: data, Channel: ctx.Channel, Client: ctx.Client}
	routeHandler, err := page_handle.RouteHandler(handleCtx)
	if err != nil {
		log.Println(err.Error())
	} else {
		handleCtx, err = routeHandler.Handle()
		logicMetas := getLinkPageLogicMetas(logicMeta)
		if logicMetas != nil && len(logicMetas) > 0 {
			for _, lm := range logicMetas {
				ctx.doHandle(lm, data)
			}
		}
	}
}

func getLinkPageLogicMetas(logicMeta *models.PageLogicMeta) []*models.PageLogicMeta {

	return nil
}
